package main;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.TimerTask;

import main.Sync_app.Address;

public class ClientThread extends TimerTask {
  private final Address address;
  
  public ClientThread(Address a) {
    address = a;
  }
  
  @Override public void run() {
    Sync_app.writeEndOfFileString();
    byte[] mybytearray = createHelloMsg();
    Socket sock = null;
    OutputStream os = null;
    try {
      sock = new Socket(address.ip, address.port);
    } catch (IOException e) {
      System.out.println("neighbor: " + address.ip + " is not connected");
    }
    try {
      if (sock != null) {
        os = sock.getOutputStream();
        os.write(mybytearray, 0, mybytearray.length);
        os.flush();
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (os != null)
          os.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
      try {
        if (sock != null)
          sock.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  
  private byte[] createHelloMsg() {
    String s = Sync_app.HELLO_MSG_STR + " " + Sync_app.getLastModified() + " " + Sync_app.myPort;
    return s.getBytes();
  }
}